/**
 * Created by Qingger Corp.
 * User: jsspf
 * Date: 2018/1/2
 * Time: 17:18
 */
import {Context} from "koa";
import {BlogController} from "../../dist/src/controllers/blogs";
const Router = require("koa-router");
const body = require('koa-better-body');

/**
 * 注意路由定义的方法:
 *  1) router = new Router({prefix});  // 定义路由实例,prefix可选
 *  2) router.get|post|put|delete(name? , prefix, functionImplement);  // 路由方法定义,第一个参数name可选
 *  3) router.url(routerName,params?);  // 路由别名定义
 *  4) router.use(prefix?, routerInsMiddleware,routerAllowedMethods ); // 子路由，路由中间件
 *  5) router.routes() : Function;                // 所定义的路由闭包, 用来作中间件或子路由
 *  6) router.allowedMethods() : Function;        // 所定义的路由闭包, 用来作中间件或子路由
 */

/**
 * router.get|put|post|patch|delete|del
 * @type {Router}
 */
const userRouter = new Router({
    // 路由前缀定义
    prefix: '/user'
});
userRouter
    .get('/',(ctx:Context,next:Function)=>{
        ctx.body = "hhhh";
        // ctx.body = {url:ctx.request.url, method:ctx.request.method, postBody: "[WARNING] : GET USER/ IS NOT SUPPORT"};
    })
    .post('/',(ctx:Context,next:Function)=>{
        ctx.body = {url:ctx.request.url, method:ctx.request.method, postBody: "[WARNING] : NOT IMPLEMENT....."};
    })
    .put('/:id',(ctx:Context,next:Function) => {
        ctx.body = {url:ctx.request.url, method:ctx.request.method, queryUserId:ctx.params['id']};
    })
    .delete('/:id',(ctx:Context,next:Function) => {
        ctx.body = {url:ctx.request.url, method:ctx.request.method, queryUserId:ctx.params['id']};
    })
    // 当所有动词不匹配时，使用all
    .all('/:id',(ctx:Context,next:Function) => {
        ctx.body = {url:ctx.request.url, method:ctx.request.method, queryUserId:ctx.params['id'], ACTION:"ALL"}
    });


/**
 * 具名路由
 * @type {Router}
 */
const blogRouter = new Router();
// blogRouter.use(body());
// blogRouter.get('blog','/blog/:id',(ctx:Context,next:Function) => {
//       ctx.body = {url:ctx.request.url, method:ctx.request.method, queryBlogId: ctx.params['id']}
// });
// blogRouter.get("/blogs/:id", (ctx:Context,next:Function) => {
//     // 使用router.url方法改变路由方法(通过定义路由名称)
//    blogRouter.url("blog",ctx.params['id']);
// });
blogRouter
    .get('getBlog',"/blog/:id",(ctx:Context) => {
        let url = ctx.url;
        let request = ctx.request;
        ctx.body = {
            url,
            ctxQuery : ctx.querystring
        }
    })
    .post('postBlog','/blog',body(),BlogController.postBlogDetail);


/**
 * 子路由 : Nested routers
 * @type {Router}
 */
const forumsRouter = new Router();
const postsRouter = new Router();
postsRouter.get('/',(ctx:Context,next:Function) => {
    ctx.body = {url:ctx.request.url, method:ctx.request.method, queryParams: ctx.params}
});
postsRouter.get('/:pid',(ctx:Context,next:Function) => {
    ctx.body = {url:ctx.request.url, method:ctx.request.method, queryParams: ctx.params}
});
// responds to "/forums/123/posts" and "/forums/123/posts/123"
forumsRouter.use('/forums/:fid/posts',postsRouter.routes(),postsRouter.allowedMethods());


/**
 * 中间件定义,可以使用Promise
 * @param {Application.Context} ctx
 * @param {Function} next
 */
function doAuth(ctx:Context,next:Function) {
   const checkParamId =   new Promise(function(resolve,reject){
       if (ctx.params.id && ctx.params.id > 1000) {
           resolve(true);
       } else {
           reject(false);
       }
   });
    return checkParamId.then(function(ret:boolean){
        // 中间件一般是符合一些规则了，就直接next
        next();
    }).catch(function(err:boolean){
        console.error("Auth Failed");
        ctx.status = 501;
        throw new Error("Auth Failed");
    })
}
// 使用中间件
const baseAdminAuthRouter = new Router();
baseAdminAuthRouter.get('/admin/:id',doAuth,(ctx:Context,next:Function) => {
    ctx.body = {url:ctx.request.url, method:ctx.request.method,AuthInfo: ctx.params};
});

// 中间件也可以直接use来定义, 注意:path可以多个
// userRouter一旦用作中间件，就不能访问 /user/:id 了？？？
// const authRouter = new Router();
// authRouter.use(['/auth','/admin'],doAuth,userRouter.routes(),userRouter.allowedMethods);



/**
 * 重定向路由示例
 * @type {Router}
 */
const signInRouter = new Router();
signInRouter.get('/sign-in',function (ctx:Context,next:Function) {
    ctx.body = "<div> LOGIN In APP : SIGN For User</div>";
});
signInRouter.all('/login',(ctx:Context,next:Function) => {
    // ctx.redirect(ctx.router.url('sign-in'));
    ctx.redirect('/sign-in');
    ctx.status = 301;
});


const appRouter = new Router();
appRouter.use(userRouter.routes(),userRouter.allowedMethods());
appRouter.use(blogRouter.routes(),blogRouter.allowedMethods());
appRouter.use(forumsRouter.routes(),forumsRouter.allowedMethods());
appRouter.use(baseAdminAuthRouter.routes(),baseAdminAuthRouter.allowedMethods());
appRouter.use(signInRouter.routes(),signInRouter.allowedMethods());

export {appRouter};